<script lang="ts" setup>
import {
  computed,
  onMounted,
  onUnmounted,
  type Ref,
  ref,
  watch,
  inject,
} from 'vue';
// icon
import LogoIcon from '@/icons/logo.svg?component';
import LogoIconMobile from '@/icons/logo_mobile.svg?component';
// import WalletIcon from '@/icons/wallet.svg?component'
import EnFlag from '@/icons/en.svg?url';
import IdFlag from '@/icons/id.svg?url';
import JaFlag from '@/icons/ja.svg?url';
import KoFlag from '@/icons/ko.svg?url';
import ViFlag from '@/icons/vi.svg?url';
import EsFlag from '@/icons/es.svg?url';
import ArFlag from '@/icons/ar.svg?url';
import RuFlag from '@/icons/ru.svg?url';
import FrFlag from '@/icons/fr.svg?url';
import PtFlag from '@/icons/pt.svg?url';
import HiFlag from '@/icons/hi.svg?url';
import ZhCnFlag from '@/icons/zh_cn.svg?url';
import ZhTwFlag from '@/icons/zh_tw.svg?url';
import ThFlag from '@/icons/th.svg?url';
import { useRoute, useRouter } from 'vue-router';

// Components
import DrawerComponent from '@/components/DrawerComponent.vue';

// Stores
import GlobalStore from '@/store/GlobalStore';

// import useWalletHook from '@/hooks/Wallet'
import storage from '@/utils/storage';
import { useI18n } from 'vue-i18n';
// import WalletStore from "@/store/WalletStore";
import WalletStore from '@/store/WalletStore';
import BindSocialDialog from '@/components/BindSocialDialog.vue';
import UserStore from '@/store/UserStore';
import { storeToRefs } from 'pinia';
import useContractHook from '@/hooks/Contract';
import useWalletHook from '@/hooks/Wallet';
import Dialog from '@/components/dialog/dialog';
import { bindSocialAccountApi } from '@/api/system/user';

const {
  connect,
  isSupportedNetwork,
  userDisplayName,
  connectStatus,
  walletAddress,
  provider,
  disconnect,
} = useWalletHook();

const { t } = useI18n();

const emitter = inject('emitter');

/** Global Store */
const globalStore = GlobalStore();
const walletStore = WalletStore();
// const isSupportedNetwork = computed(() => {
//   return walletStore.isSupportedNetwork
// })
// const userDisplayName = computed(() => {
//   return walletStore.userDisplayName
// })
// const connectStatus = computed(() => {
//   return walletStore.connectStatus
// })

/** drawer visibility */
const drawer: Ref<boolean> = ref(false);
// const walletAddr = computed(() => {
//   return formatAddress(storage.getItem('walletAddress'))
// })
// wallet text
// console.log('wallet address:', walletAddress.value)
// const walletText = ref<string>(walletStore.walletAddress ? walletStore.walletAddress : t('message.system.nav.connect'))
const walletText = computed(() => {
  return walletAddress.value
    ? walletAddress.value
    : t('message.system.nav.connect');
});
const lang = ref<string>(
  storage.getItem('lang') !== undefined ? storage.getItem('lang') : 'en'
);
const langOptions = [
  {
    lang: 'en',
    flag: EnFlag,
  },
  {
    lang: 'es',
    flag: EsFlag,
  },
  {
    lang: 'fr',
    flag: FrFlag,
  },
  {
    lang: 'pt',
    flag: PtFlag,
  },
  {
    lang: 'ru',
    flag: RuFlag,
  },
  {
    lang: 'ar',
    flag: ArFlag,
  },

  {
    lang: 'ja',
    flag: JaFlag,
  },
  {
    lang: 'ko',
    flag: KoFlag,
  },
  {
    lang: 'zh_cn',
    flag: ZhCnFlag,
  },
  {
    lang: 'zh_tw',
    flag: ZhTwFlag,
  },
  {
    lang: 'hi',
    flag: HiFlag,
  },
  {
    lang: 'vi',
    flag: ViFlag,
  },
  {
    lang: 'id',
    flag: IdFlag,
  },
  {
    lang: 'th',
    flag: ThFlag,
  },
];
// const showLangDropdown = ref<boolean>(false)
const menus = [
  {
    icon: 'mdi-account-multiple-check-outline',
    title: t('message.system.nav.menus.social'),
    to: '#',
  },
  {
    icon: 'mdi-account-outline',
    title: t('message.system.nav.menus.profile'),
    // to: `/profile/${storage.getItem('lang')}`
    to: '/profile',
  },
  {
    icon: 'mdi-view-dashboard-variant-outline',
    title: t('message.system.nav.menus.dashboard'),
    // to: `/dashboard/${storage.getItem('lang')}`
    to: '/dashboard',
  },
  {
    icon: 'mdi-export',
    title: t('message.system.nav.menus.disconnect'),
    // to: `/dashboard/${storage.getItem('lang')}`
    to: 'disconnect',
  },
];

const router = useRouter();

const flagIcon = (lang: string) => {
  const existFlag = langOptions.find(item => item.lang === lang);
  if (existFlag) {
    return existFlag.flag;
  } else {
    return EnFlag;
  }
};

// const switchLangOptions = () => {
//   showLangDropdown.value = !showLangDropdown.value
// }

const hiddenDrawer = (show: boolean) => {
  console.log('value passed from child:', show);
  drawer.value = show;
  globalStore.$patch({
    _showMobileMenu: drawer.value,
  });
};

const openUrl = (url: string) => {
  window.open(url);
};

const setMenuFold = () => {
  drawer.value = !drawer.value;
  console.log('setMenuFold:', drawer.value);
  globalStore.$patch({
    _showMobileMenu: drawer.value,
  });
  console.log(globalStore._showMobileMenu);
};

const changeLang = (selectedLang: string) => {
  console.log('lang:', selectedLang);
  storage.setItem('lang', selectedLang.toLowerCase());
  lang.value = selectedLang.toLowerCase();
  // let url
  // if (location.href.includes('?')) {
  //   url =
  //     location.href.substring(0, location.href.lastIndexOf('/') + 1) +
  //     selectedLang.toLowerCase() +
  //     location.href.substring(location.href.indexOf('?'), location.href.length - 1)
  // } else {
  //   url =
  //     location.href.substring(0, location.href.lastIndexOf('/') + 1) + selectedLang.toLowerCase()
  // }
  // location.replace(url)

  // TODO
  location.reload();
};

const modules = import.meta.globEager('../../assets/images/avatars/**.png');
// console.log('modules:', modules)
const index = Math.floor(Math.random() * (7 + 1));
// console.log('index:', index)
let avatar;
Object.keys(modules).forEach(key => {
  const jsonName = key.substring(key.lastIndexOf('\/') + 1, key.length);
  const avatarName = jsonName.substring(
    jsonName.indexOf('_') + 1,
    jsonName.indexOf('.')
  );
  if (parseInt(avatarName) - 1 === index) {
    // @ts-ignore
    avatar = modules[key].default;
  }
});

const userStore = UserStore();

const bindDialogOpen = ref<boolean>(false);
const bindInfo = ref<any>({
  telegram: false,
  discord: false,
});
const showMenu = ref<boolean>(false);
console.log('storage tab:', storage.getItem('tab'));
const { _tab } = storeToRefs(globalStore);
const tabs = [
  {
    tab: t('message.system.nav.home'),
    to: 'Home',
  },
  {
    tab: t('message.system.nav.proposal'),
    to: 'Proposal',
  },
  {
    tab: t('message.system.nav.ido'),
    to: 'IDO',
  },
  {
    tab: 'NFT',
    to: 'NFT',
  },
  {
    tab: t('message.system.nav.dashboard'),
    to: 'Dashboard',
  },
];

const { userInfo } = storeToRefs(userStore);

const route = useRoute();

const { startPolling } = useContractHook();

const connectWallet = () => {
  // walletStore.connect().then(async () => {
  connect().then(async () => {
    console.log('connect userInfo:', userInfo.value);
    // Start polling for data
    await startPolling();
    if (userInfo.value) {
      // @ts-ignore
      const tgId = userInfo.value?.tgId;
      // @ts-ignore
      const dcId = userInfo.value?.dcId;
      if (tgId !== null) {
        bindInfo.value.telegram = true;
      } else {
        bindInfo.value.telegram = false;
      }
      if (dcId !== null) {
        bindInfo.value.discord = true;
      } else {
        bindInfo.value.discord = false;
      }

      // if (dcId !== null && tgId !== null) {
      //   bindDialogOpen.value = false;
      // } else {
      //   bindDialogOpen.value = true;
      // }
    }
  });
};

const onClickMenu = (menu: any) => {
  showMenu.value = false;
  if (menu.to === '#') {
    bindDialogOpen.value = true;
  } else if (menu.to === 'disconnect') {
    disconnectWallet();
  } else {
    router.push(menu.to);
    // location.reload();
  }
};

const onClickTab = (item: any) => {
  _tab.value = item.to;
  console.log('tab:', _tab.value);
  globalStore.setTab(_tab.value);

  if (item.to === 'Proposal') {
    openUrl('https://vote.sdao.win/#/');
  } else {
    router.push({ name: item.to });
    // location.reload();
  }
};

const onClickHome = () => {
  router.push('/');
  // location.reload();
  _tab.value = 'Home';
  storage.setItem('tab', 'Home');
};

const disconnectWallet = async () => {
  await disconnect();
  userStore.resetState();
  localStorage.removeItem('WEB3_CONNECT_CACHED_PROVIDER');
  if (localStorage.getItem('walletconnect')) {
    localStorage.removeItem('walletconnect');
  } else if (localStorage.getItem('WALLETCONNECT')) {
    localStorage.getItem('WALLETCONNECT');
  }
  location.reload();
};

let flag;
const init = () => {
  // telegram bot or discord bot bind account
  if (
    (route.query.name && route.query.tgId) ||
    (route.query.name && route.query.dcId)
  ) {
    flag = false;
    const interval = window.setInterval(() => {
      if (walletAddress.value !== undefined) {
        if (flag) {
          clearInterval(interval);
          return;
        }

        const tgId = route.query.tgId;
        const dcId = route.query.dcId;
        const accountName = route.query.name;
        const bindType = tgId ? 2 : 1;
        bindSocialAccountApi({
          accountId: tgId ? tgId : dcId,
          accountName: accountName,
          type: bindType,
        })
          .then((res: any) => {
            console.log('bindSocialApi res:', res);
            let userInfo: any;
            if (bindType === 2) {
              bindInfo.value.telegram = true;
              userInfo = {
                ...userStore.userInfo,
                tgId: res,
              };
            } else {
              bindInfo.value.discord = true;
              userInfo = {
                ...userStore.userInfo,
                dcId: res,
              };
            }

            userStore.setUserInfo(userInfo);

            showBindDialog();

            flag = true;
          })
          .catch((err: any) => {
            console.log('bind social err:', err);
          });
        if (bindType === 2) {
          // @ts-ignore
          emitter.emit('botBind', 'tg');
        } else {
          // @ts-ignore
          emitter.emit('botBind', 'dc');
        }
        clearInterval(interval);
      }
    }, 1000);
  } else {
    showBindDialog();
  }
};

const showBindDialog = () => {
  // @ts-ignore
  const tgId = userInfo.value?.tgId;
  console.log('userInfo init:', userInfo.value);
  console.log('tgId:', tgId);
  if (tgId !== null) {
    bindInfo.value.telegram = true;
  } else {
    bindInfo.value.telegram = false;
  }
  // @ts-ignore
  const dcId = userInfo.value?.dcId;
  console.log('dcId:', dcId);
  if (dcId !== null) {
    bindInfo.value.discord = true;
  } else {
    bindInfo.value.discord = false;
  }

  if (userInfo.value) {
    if (dcId !== null && tgId !== null) {
      bindDialogOpen.value = false;
    } else {
      bindDialogOpen.value = true;
    }
  }
};

// init();

onMounted(async () => {
  // 刷新页面重新连接钱包
  console.log('cache:', localStorage.getItem('WEB3_CONNECT_CACHED_PROVIDER'));
  if (
    localStorage.getItem('WEB3_CONNECT_CACHED_PROVIDER') &&
    walletAddress.value === undefined
  ) {
    console.log('enter');
    await connectWallet();
    console.log('wallet address:', walletAddress.value);
    console.log('provider:', provider.value);
  }

  // 滚动时固定连接钱包提示
  // 滚动到距离开头的200px开始固定导航
  const headerEl: any = document.querySelector('.bind-social-tooltip');
  window.addEventListener('scroll', () => {
    const height = headerEl.getBoundingClientRect().height;
    if (window.pageYOffset - height > 120) {
      if (!headerEl.classList.contains('sticky')) {
        headerEl.classList.add('sticky');
      }
    } else {
      headerEl.classList.remove('sticky');
    }
  });
});

onUnmounted(() => {
  const headerEl: any = document.querySelector('.bind-social-tooltip');
  window.removeEventListener('scroll', () => {
    const height = headerEl.getBoundingClientRect().height;
    if (window.pageYOffset - height > 200) {
      if (!headerEl.classList.contains('sticky')) {
        headerEl.classList.add('sticky');
      }
    } else {
      headerEl.classList.remove('sticky');
    }
  });
});

watch(
  () => isSupportedNetwork.value,
  () => {
    if (!isSupportedNetwork.value) {
      // TODO 待国际化
      Dialog('Not support network, please add bsc network');
    }
  }
);

watch(
  () => walletAddress.value,
  async newVal => {
    if (newVal !== undefined) {
      if (
        (route.query.name && route.query.tgId) ||
        (route.query.name && route.query.dcId)
      ) {
        await init();
      }
    }
  }
);
</script>

<template>
  <v-navigation-drawer
    v-show="drawer"
    :model-value="drawer"
    class="hidden-sm-and-up m-tabs"
    absolute
    bottom
    temporary
    style="
      width: 80% !important;
      z-index: 100008;
    "
  >
    <drawer-component @hidden="hiddenDrawer" />
  </v-navigation-drawer>

  <v-app-bar color="#CDDFF7" elevate-on-scroll app class="nav-header">
    <v-app-bar-nav-icon
      class="hidden-sm-and-up"
      :class="drawer ? 'transform-icon' : ''"
      @click="setMenuFold"
    >
      <v-icon v-if="!drawer" color="#7A7893">mdi-menu</v-icon>
      <v-icon v-else color="#7A7893">mdi-menu-open</v-icon>
    </v-app-bar-nav-icon>
    <logo-icon
      class="logo-icon hidden-sm-and-down cursor-pointer"
      @click="onClickHome"
    />
    <logo-icon-mobile
      class="logo-icon hidden-sm-and-up cursor-pointer"
      @click="onClickHome"
    />

    <v-spacer />

    <v-tabs class="nav-tabs hidden-sm-and-down" :model-value="_tab">
      <v-tab
        v-for="(item, index) in tabs"
        :key="index"
        :value="item.to"
        @click.stop="onClickTab(item)"
      >
        <span>{{ item.tab }}</span>
      </v-tab>
    </v-tabs>

    <div
      class="d-flex flex-row justify-center wallet-wrapper items-center relative"
    >
      <v-avatar size="30px" class="mr-2">
        <v-img :src="avatar" />
      </v-avatar>
      <span
        v-if="userDisplayName"
        class="display-name"
        @click="showMenu = !showMenu"
      >
        {{ userDisplayName }}
      </span>
      <span
        v-else-if="!connectStatus"
        class="wallet"
        @click.stop="connectWallet"
      >
        {{ walletText }}
      </span>

      <v-menu activator="parent" :model-value="showMenu" class="dropdown-menu">
        <v-list class="mt-1 -ml-4" bg-color="white">
          <v-list-item
            v-for="(item, index) in menus"
            :key="index"
            :value="index"
            @click.stop="onClickMenu(item)"
          >
            <div class="flex flex-row">
              <v-icon color="#736B7D">{{ item.icon }}</v-icon>
              <v-list-item-title class="text-[16px] text-[#736B7D] ml-3">
                {{ item.title }}
              </v-list-item-title>
            </div>
          </v-list-item>
        </v-list>
      </v-menu>
    </div>

    <div class="lang-wrapper">
      <div style="background: white; padding: 6px; border-radius: 50%">
        <v-avatar size="26px" color="white">
          <v-img :src="flagIcon(lang)" class="flag-icon" />
        </v-avatar>

        <v-menu offset-y-10 activator="parent" class="flag-list">
          <v-list
            rounded
            width=""
            bg-color="white"
            class="xs:grid xs:grid-cols-2 xs:gap-6 xs:h-fit xs:w-fit"
          >
            <img
              v-for="(item, index) in langOptions"
              :key="index"
              :src="flagIcon(item.lang)"
              class="flag-icon"
              @click.stop="changeLang(item.lang)"
            />
          </v-list>
        </v-menu>
      </div>
    </div>

    <!--      夜间模式-->
    <!--      <app-bar-menu-component />-->
  </v-app-bar>

  <div v-show="!walletStore.userDisplayName" class="bind-social-tooltip">
    {{ t('message.system.nav.link') }}
  </div>

  <bind-social-dialog
    v-show="
      walletStore.userDisplayName !== '' &&
      (bindInfo.telegram === false || bindInfo.discord === false)
    "
    v-model:is-bind-dialog-open="bindDialogOpen"
    :bind-info="bindInfo"
  />
</template>

<style scoped lang="scss">
// 头部导航条样式
.v-app-bar.v-toolbar:not(.v-toolbar--flat) {
  box-shadow: none !important;
}

.nav-tabs {
  margin-right: 40px;

  span {
    color: #7a7893 !important;
  }

  ::v-deep .v-tab__slider {
    color: #2b6eef !important;
  }
}

.m-tabs {
  padding-top: 60px;
  overflow: hidden;

  ::v-deep .v-list {
    font-size: 32px;
    font-weight: bold;
    color: #7a7893;
  }
}

.flag-list {
  ::v-deep .v-list {
    margin-top: 8px;
    padding: 18px 0;
    border-radius: 32px;
    @apply xs:rounded-lg xs:p-4;
  }

  .flag-icon {
    margin: 0 auto;
    width: 24px;
    height: 24px;
    cursor: pointer;

    &:not(:last-of-type) {
      margin-bottom: 16px;
      @apply xs:mb-0;
    }

    &:last-of-type {
      margin-bottom: 6px;
    }

    &:first-child {
      margin-top: 6px;
      @apply xs:mt-0;
    }
  }

  ::v-deep .v-overlay__content {
    @apply xs:right-1 xs:left-[unset] #{!important};
  }
}

::v-deep .v-slide-group__content {
  justify-content: center;
  align-items: center;
}

::v-deep .v-menu .v-overlay__content {
  align-items: center;
  background: white;
  padding-top: 17px;
  padding-bottom: 17px;
  border-radius: 23px;
  top: 87px !important;
  box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.15);

  :not(:last-of-type(.flag-icon)) {
    margin-bottom: 16px;
  }
}

@media screen and (min-width: 601px) {
  // 头部导航条样式
  .nav-header {
    padding-left: 96px;
    padding-right: 96px;
  }

  .transform-icon {
    ::v-deep .mdi-menu {
      transform: rotate(90deg);
    }
  }

  ::v-deep .v-toolbar__content {
    //@apply h-28;
    height: 120px !important;
  }
  .logo-icon {
    width: 304px;
    height: 34px;
  }
}

@media screen and (max-width: 600px) {
  // 头部导航条样式
  .nav-header {
    padding-left: 8px;
    padding-right: 8px;
  }
  ::v-deep .v-toolbar__content {
    height: 60px !important;
  }
  .logo-icon {
    width: 100px;
    height: 12px;
  }
}

// 钱包
.wallet-wrapper {
  margin-right: 10px;
  cursor: pointer;
  height: max-content;
  @apply xs:p-2 xl:px-3 xl:py-2 lg:px-3 lg:py-2 md:px-4 md:py-3 sm:px-3 sm:py-2.5 rounded-full bg-white;

  .wallet {
    font-size: 14px;
    color: #7a7893 !important;
    white-space: nowrap;
    @apply ml-2;
  }
  .display-name {
    color: #7a7893 !important;
  }
}

.bind-social-tooltip {
  background: #ffffff;
  box-shadow: 0px 0px 8px 0px rgba(193, 193, 193, 0.5);
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #736b7d;
  line-height: 26px;
  border-radius: 8px;
  z-index: 99999;
  @apply p-5 w-80 mt-14 absolute top-10 right-36 xs:right-10 xs:top-2;
}

.bind-social-tooltip:before {
  content: '';
  position: absolute;
  right: 40px;
  top: -4px;
  padding: 10px;
  border: inherit;
  border-right: 0;
  border-bottom: 0;
  border-radius: 0.2rem;
  background: inherit;
  transform: rotate(45deg);
}

// 滚动时固定连接钱包提示
.sticky {
  position: fixed;
  background-color: white;
  box-shadow: 0 0 18px rgba(0, 0, 0, 0.2);
  transition: dropDown 0.6s ease-in-out;
  // 定义固定导航动画效果
  @keyframes dropDown {
    from {
      transform: translateY(-100px); // 移动窗口上面的100px
    }
    to {
      transform: translateY(0px); // 恢复到原来的地方
    }
  }
}
</style>
